package com.ydzt.fanka.server.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.domain.StatisticsInfo;
import com.ydzt.fanka.server.init.InitData;

public class PackageHelper {
	static Logger logger = Logger.getLogger(PackageHelper.class.getName());
	private static int oneRecordLength = 43;
	private static int seqNo = 0;
	
	static byte[] byteArrayCurrentStmtDay;
	static byte[] typeBytes;
	static byte[] pkg_2002;
	static byte[] sender;
	static byte[] recevier;
	static byte[] byteArrayport;
	static byte[] msgMgrType;
	static byte[] seq;
	static byte[] pkgno;
	static byte[] lastFlagBytes;
	static byte[] recordcount;
	static byte[] agm;
	
	public static byte[] createPkg2003(String stmtDay,String receiverID){
		try{
			String tmp;
			logger.info("组2003报文");
			int offsetHead = 0;
			byteArrayCurrentStmtDay = new byte[4];
			//组2001报文给中心
			pkg_2002 = new byte[27];
			byteArrayCurrentStmtDay = ByteConvert.str2BcdNormal(stmtDay); 
			typeBytes = ByteConvert.str2BcdNormal("2003");
			sender = ByteConvert.str2BcdNormal(InitData.nodeType + "000000");
		    //sender = ByteConvert.ipv4Address2BinaryArray(NetUtil.getIp());//4
		    logger.info("发送方:" + InitData.nodeType + "000000");
		    tmp = InitData.getInstance().getSupplierMap().get(receiverID);
		    if(tmp == null){
		    	logger.info("查询不到节点" + receiverID + "对应的IP及端口");
		    }
		    else{
		    	recevier = ByteConvert.str2BcdNormal(receiverID);
			    byteArrayport = ByteConvert.shortToBytes((short)0);
			    msgMgrType = new byte[1];
			    msgMgrType[0] = 0x00;//只入库
				seq = ByteConvert.intToBytes(0);
				pkgno = ByteConvert.shortToBytes((short)1);
				lastFlagBytes = new byte[1];//1
				lastFlagBytes[0] = 0x01;
				recordcount = ByteConvert.shortToBytes((short)1);//2
				agm = new byte[1];
				agm[0] = 0x00;//1
				System.arraycopy(typeBytes, 0, pkg_2002, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(sender, 0, pkg_2002, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(recevier, 0, pkg_2002, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(byteArrayport, 0, pkg_2002, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(msgMgrType, 0, pkg_2002, offsetHead, 1);
				offsetHead += 1;
				System.arraycopy(seq, 0, pkg_2002, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(pkgno, 0, pkg_2002, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(lastFlagBytes, 0, pkg_2002, offsetHead, 1);
				offsetHead += 1;
				System.arraycopy(recordcount, 0, pkg_2002, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(agm, 0, pkg_2002, offsetHead, 1);
				offsetHead += 1;
				System.arraycopy(byteArrayCurrentStmtDay, 0, pkg_2002, offsetHead, 4);
		    }
		}catch(Exception e){
			logger.error("执行createPkg2003发生错误:" + e.getMessage());
		}
		return pkg_2002;
	}
	
	public static byte[] createPkg2002(String stmtDay,String receiverID){
		try{
			String tmp;
			logger.info("组2002报文");
			int offsetHead = 0;
			byteArrayCurrentStmtDay = new byte[4];
			//组2001报文给中心
			pkg_2002 = new byte[27];
			byteArrayCurrentStmtDay = ByteConvert.str2BcdNormal(stmtDay); 
			typeBytes = ByteConvert.str2BcdNormal("2002");
			sender = ByteConvert.str2BcdNormal(InitData.nodeType + "000000");
		    //sender = ByteConvert.ipv4Address2BinaryArray(NetUtil.getIp());//4
		    logger.info("发送方:" + InitData.nodeType + "000000");
		    tmp = InitData.getInstance().getSupplierMap().get(receiverID);
		    if(tmp == null){
		    	logger.info("查询不到节点" + receiverID + "对应的IP及端口");
		    }
		    else{
		    	recevier = ByteConvert.str2BcdNormal(receiverID);
			    byteArrayport = ByteConvert.shortToBytes((short)0);
			    msgMgrType = new byte[1];
			    msgMgrType[0] = 0x00;//只入库
				seq = ByteConvert.intToBytes(0);
				pkgno = ByteConvert.shortToBytes((short)1);
				lastFlagBytes = new byte[1];//1
				lastFlagBytes[0] = 0x01;
				recordcount = ByteConvert.shortToBytes((short)1);//2
				agm = new byte[1];
				agm[0] = 0x00;//1
				System.arraycopy(typeBytes, 0, pkg_2002, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(sender, 0, pkg_2002, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(recevier, 0, pkg_2002, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(byteArrayport, 0, pkg_2002, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(msgMgrType, 0, pkg_2002, offsetHead, 1);
				offsetHead += 1;
				System.arraycopy(seq, 0, pkg_2002, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(pkgno, 0, pkg_2002, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(lastFlagBytes, 0, pkg_2002, offsetHead, 1);
				offsetHead += 1;
				System.arraycopy(recordcount, 0, pkg_2002, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(agm, 0, pkg_2002, offsetHead, 1);
				offsetHead += 1;
				System.arraycopy(byteArrayCurrentStmtDay, 0, pkg_2002, offsetHead, 4);
		    }
		}catch(Exception e){
			logger.error("执行createPkg2002发生错误:" + e.getMessage());
		}
		return pkg_2002;
	}
	
	/*
	 * 在日终时 对当日明细进行统计 并将统计信息组包为3001报文
	 * */
	public static byte[] createPackageAboutStatisticsCentre(String nodeType,String stmtDay){
		List<StatisticsInfo> statisticsList = new ArrayList<StatisticsInfo>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		byte[] pkg = null;
		String tmp = InitData.getInstance().getSupplierMap().get(nodeType);
		if(tmp!=null){
			logger.info("查询统计信息详细情况");
			String sqlText = "select * from TBL_CENTRE_TRANSACTION_DAY where stmt_day = '" + stmtDay + "' and SUPPLIER_ID = '" + nodeType.substring(0, 2) + "'";
			logger.info("根据:" + sqlText + " 查询");
			try {
				conn = JdbcUtils.getConnectionForOracle();
				conn.setAutoCommit(false);
				pstmt = conn.prepareStatement(sqlText);
				rs = pstmt.executeQuery();
				while(rs.next()){
					StatisticsInfo statisticsInfo = new StatisticsInfo();
					statisticsInfo.setSupplier_id(rs.getString("SUPPLIER_ID").trim());
					statisticsInfo.setStmt_day(rs.getString("STMT_DAY").trim());
					statisticsInfo.setCard_type(rs.getInt("CARD_TYPE"));
					statisticsInfo.setTrans_type(rs.getInt("TRANS_TYPE"));
					statisticsInfo.setExcept_type(rs.getInt("EXCEPT_TYPE"));
					statisticsInfo.setTimes(rs.getLong("TIMES"));
					statisticsInfo.setAmount(rs.getLong("AMOUNT"));
					statisticsInfo.setDeposit(rs.getLong("DEPOSIT"));
					statisticsInfo.setErr_code(rs.getString("ERR_CODE"));
					statisticsInfo.setDept_id(rs.getString("DEPT_ID"));
					statisticsList.add(statisticsInfo);
				}
				conn.commit();
				conn.setAutoCommit(true);
			    int recordCount = statisticsList.size();
			  //计算包体长度
			    int bodyLenth = oneRecordLength * recordCount;
			    pkg = new byte[23 + bodyLenth];
			    int offsetHead = 0;
			    for(int i = 0; i < recordCount; i ++){
			    	int offset = 0;
			    	byte[] oneRecordByte = new byte[oneRecordLength];
			    	byte[] supplier_id = ByteConvert.str2BcdNormal(statisticsList.get(i).getSupplier_id());
			    	System.arraycopy(supplier_id, 0, oneRecordByte, offset, 1);
			    	offset += 1;
			    	byte[] stmt_day = ByteConvert.str2BcdNormal(statisticsList.get(i).getStmt_day());
			    	System.arraycopy(stmt_day, 0, oneRecordByte, offset, 4);
			    	offset += 4;
			    	byte[] card_type = ByteConvert.intToBytes(statisticsList.get(i).getCard_type());
			    	System.arraycopy(card_type, 0, oneRecordByte, offset, 4);
			    	offset += 4;
			    	byte[] trans_type = ByteConvert.intToBytes(statisticsList.get(i).getTrans_type());
			    	System.arraycopy(trans_type, 0, oneRecordByte, offset, 4);
			    	offset += 4;
			    	byte[] except_type = ByteConvert.intToBytes(statisticsList.get(i).getExcept_type());
			    	System.arraycopy(except_type, 0, oneRecordByte, offset, 4);
			    	offset += 4;
			    	byte[] times = ByteConvert.longToBytes(statisticsList.get(i).getTimes());
			    	System.arraycopy(times, 0, oneRecordByte, offset, 8);
			    	offset += 8;
			    	byte[] amount = ByteConvert.longToBytes(statisticsList.get(i).getAmount());
			    	System.arraycopy(amount, 0, oneRecordByte, offset, 8);
			    	offset += 8;
			    	byte[] deposit = ByteConvert.longToBytes(statisticsList.get(i).getDeposit());
			    	System.arraycopy(deposit, 0, oneRecordByte, offset, 8);
			    	offset += 8;
			    	byte[] err_code = ByteConvert.str2BcdNormal(statisticsList.get(i).getErr_code());
			    	System.arraycopy(err_code, 0, oneRecordByte, offset, 1);
			    	offset += 1;
			    	byte[] dept_id = ByteConvert.str2BcdNormal(statisticsList.get(i).getDept_id());
			    	System.arraycopy(dept_id, 0, oneRecordByte, offset, 1);
			    	offset += 1;
			    	System.arraycopy(oneRecordByte, 0, pkg, 23 + i * oneRecordLength, oneRecordLength);
			    }
			    //包头信息
			    byte[] typeBytes = ByteConvert.str2BcdNormal("3001"); //
			    byte[] sender = ByteConvert.str2BcdNormal(InitData.nodeType + "000000");
			    byte[] recevier = ByteConvert.str2Bcd(nodeType);
			    byte[] port = ByteConvert.shortToBytes((short)0);
			    byte[] msgMgrType = new byte[1];
			    if(InitData.nodeType.equals("00")){
			    	msgMgrType[0] = 0x01;//此对账报文由中心发送给食堂 食堂只入库
			    }
			    else{
			    	msgMgrType[0] = 0x01;//此对账报文由食堂发送给中心 中心只入库
			    }
				byte[] seq = ByteConvert.intToBytes(seqNo ++);
				byte[] pkgno = ByteConvert.shortToBytes((short)1);
				byte[] lastFlagBytes = new byte[1];//1
				lastFlagBytes[0] = 0x01;
				byte[] recordcount = ByteConvert.shortToBytes((short)recordCount);//2
				byte[] agm = new byte[1];
				agm[0] = 0x00;//1
				System.arraycopy(typeBytes, 0, pkg, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(sender, 0, pkg, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(recevier, 0, pkg, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(port, 0, pkg, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(msgMgrType, 0, pkg, offsetHead, 1);
				offsetHead += 1;
				System.arraycopy(seq, 0, pkg, offsetHead, 4);
				offsetHead += 4;
				System.arraycopy(pkgno, 0, pkg, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(lastFlagBytes, 0, pkg, offsetHead, 1);
				offsetHead += 1;
				System.arraycopy(recordcount, 0, pkg, offsetHead, 2);
				offsetHead += 2;
				System.arraycopy(agm, 0, pkg, offsetHead, 1);
				offsetHead += 1;
			    
			} catch (SQLException e) {
				logger.error("查询日终状态出错:" + e.getMessage());
				try{
					if(conn != null){
						conn.rollback();
						conn.setAutoCommit(true);
					}
				}
				catch(SQLException e2){
				}
			} finally{
				JdbcUtils.freeAll(rs, pstmt, conn);
			}
		}
		return pkg;
	}
	
	/*
	 * 在日终时 对当日明细进行统计 并将统计信息组包为3001报文
	 * */
	public static byte[] createPackageAboutStatistics(){
		byte[] pkg = null;
		List<StatisticsInfo> statisticsList = new ArrayList<StatisticsInfo>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		logger.info("查询统计信息详细情况");
		String sqlText = "select * from TBL_CENTRE_TRANSACTION_DAY where stmt_day = (select STMT_DAY from TBL_CENTRE_CLEARDAY) and SUPPLIER_ID = '" + InitData.nodeType.trim() + "'";
		logger.info("根据:" + sqlText + " 查询");
		try {
			conn = JdbcUtils.getConnectionForOracle();
			conn.setAutoCommit(false);
			pstmt = conn.prepareStatement(sqlText);
			rs = pstmt.executeQuery();
			while(rs.next()){
				StatisticsInfo statisticsInfo = new StatisticsInfo();
				statisticsInfo.setSupplier_id(rs.getString("SUPPLIER_ID").trim());
				statisticsInfo.setStmt_day(rs.getString("STMT_DAY").trim());
				statisticsInfo.setCard_type(rs.getInt("CARD_TYPE"));
				statisticsInfo.setTrans_type(rs.getInt("TRANS_TYPE"));
				statisticsInfo.setExcept_type(rs.getInt("EXCEPT_TYPE"));
				statisticsInfo.setTimes(rs.getLong("TIMES"));
				statisticsInfo.setAmount(rs.getLong("AMOUNT"));
				statisticsInfo.setDeposit(rs.getLong("DEPOSIT"));
				statisticsInfo.setErr_code(rs.getString("ERR_CODE"));
				statisticsInfo.setDept_id(rs.getString("DEPT_ID"));
				statisticsList.add(statisticsInfo);
			}
			conn.commit();
			conn.setAutoCommit(true);
		    int recordCount = statisticsList.size();
		    //计算包体长度
		    int bodyLenth = oneRecordLength * recordCount;
		    pkg = new byte[23 + bodyLenth];
		    int offsetHead = 0;
		    for(int i = 0; i < recordCount; i ++){
		    	int offset = 0;
		    	byte[] oneRecordByte = new byte[oneRecordLength];
		    	byte[] supplier_id = ByteConvert.str2BcdNormal(statisticsList.get(i).getSupplier_id());
		    	System.arraycopy(supplier_id, 0, oneRecordByte, offset, 1);
		    	offset += 1;
		    	byte[] stmt_day = ByteConvert.str2BcdNormal(statisticsList.get(i).getStmt_day());
		    	System.arraycopy(stmt_day, 0, oneRecordByte, offset, 4);
		    	offset += 4;
		    	byte[] card_type = ByteConvert.intToBytes(statisticsList.get(i).getCard_type());
		    	System.arraycopy(card_type, 0, oneRecordByte, offset, 4);
		    	offset += 4;
		    	byte[] trans_type = ByteConvert.intToBytes(statisticsList.get(i).getTrans_type());
		    	System.arraycopy(trans_type, 0, oneRecordByte, offset, 4);
		    	offset += 4;
		    	byte[] except_type = ByteConvert.intToBytes(statisticsList.get(i).getExcept_type());
		    	System.arraycopy(except_type, 0, oneRecordByte, offset, 4);
		    	offset += 4;
		    	byte[] times = ByteConvert.longToBytes(statisticsList.get(i).getTimes());
		    	System.arraycopy(times, 0, oneRecordByte, offset, 8);
		    	offset += 8;
		    	byte[] amount = ByteConvert.longToBytes(statisticsList.get(i).getAmount());
		    	System.arraycopy(amount, 0, oneRecordByte, offset, 8);
		    	offset += 8;
		    	byte[] deposit = ByteConvert.longToBytes(statisticsList.get(i).getDeposit());
		    	System.arraycopy(deposit, 0, oneRecordByte, offset, 8);
		    	offset += 8;
		    	byte[] err_code = ByteConvert.str2BcdNormal(statisticsList.get(i).getErr_code());
		    	System.arraycopy(err_code, 0, oneRecordByte, offset, 1);
		    	offset += 1;
		    	byte[] dept_id = ByteConvert.str2BcdNormal(statisticsList.get(i).getDept_id());
		    	System.arraycopy(dept_id, 0, oneRecordByte, offset, 1);
		    	offset += 1;
		    	System.arraycopy(oneRecordByte, 0, pkg, 23 + i * oneRecordLength, oneRecordLength);
		    }
		    //包头信息
		    byte[] typeBytes = ByteConvert.str2BcdNormal("3001"); //2
		    byte[] sender = ByteConvert.str2Bcd(InitData.nodeType + "000000");
		    byte[] recevier = ByteConvert.str2Bcd("00000000");
		    byte[] port = ByteConvert.shortToBytes((short)0);
		    byte[] msgMgrType = new byte[1];
		    if(InitData.nodeType.equals("00")){
		    	msgMgrType[0] = 0x01;//此对账报文由中心发送给食堂 食堂只入库
		    }
		    else{
		    	msgMgrType[0] = 0x01;//此对账报文由食堂发送给中心 中心只入库
		    }
			byte[] seq = ByteConvert.intToBytes(seqNo ++);
			byte[] pkgno = ByteConvert.shortToBytes((short)1);
			byte[] lastFlagBytes = new byte[1];//1
			lastFlagBytes[0] = 0x01;
			byte[] recordcount = ByteConvert.shortToBytes((short)recordCount);//2
			byte[] agm = new byte[1];
			agm[0] = 0x00;//1
			System.arraycopy(typeBytes, 0, pkg, offsetHead, 2);
			offsetHead += 2;
			System.arraycopy(sender, 0, pkg, offsetHead, 4);
			offsetHead += 4;
			System.arraycopy(recevier, 0, pkg, offsetHead, 4);
			offsetHead += 4;
			System.arraycopy(port, 0, pkg, offsetHead, 2);
			offsetHead += 2;
			System.arraycopy(msgMgrType, 0, pkg, offsetHead, 1);
			offsetHead += 1;
			System.arraycopy(seq, 0, pkg, offsetHead, 4);
			offsetHead += 4;
			System.arraycopy(pkgno, 0, pkg, offsetHead, 2);
			offsetHead += 2;
			System.arraycopy(lastFlagBytes, 0, pkg, offsetHead, 1);
			offsetHead += 1;
			System.arraycopy(recordcount, 0, pkg, offsetHead, 2);
			offsetHead += 2;
			System.arraycopy(agm, 0, pkg, offsetHead, 1);
			offsetHead += 1;
		} catch (SQLException e) {
			logger.error("查询日终状态出错:" + e.getMessage());
			try{
				if(conn != null){
					conn.rollback();
					conn.setAutoCommit(true);
				}
			}
			catch(SQLException e2){
			}
		} finally{
			JdbcUtils.freeAll(rs, pstmt, conn);
		}
		return pkg;
	}
}
